﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;

namespace WebConfigModifier
{
    public class DocumentModifier
    {
        private readonly XDocument _doc;

        public DocumentModifier(XDocument doc)
        {
            _doc = doc;
        }

        public void ReplaceElementValue(string xPath, string value)
        {
            var element = FindElement(xPath);
            var replacementElement = XElement.Parse(value);
            element.ReplaceWith(replacementElement);
        }

        public void ReplaceAttributeValue(string xPath, string key, string value)
        {
            var element = FindElement(xPath);
            var attribute = element.Attribute(key);
            if (attribute == null) throw new WebConfigModifierException(string.Format("Could not find attribute with name '{0}'", key));
            attribute.Value = value;
        }

        private XElement FindElement(string xPath)
        {
            XmlNamespaceManager nsmrg = new XmlNamespaceManager(new NameTable());
            var element = _doc.XPathSelectElement(xPath, nsmrg);
            if (element == null) throw new WebConfigModifierException(string.Format("Could not find element with path '{0}'", xPath));
            return element;
        }
    }
}
